"""4.1 绘制词云：找一段中文文本，保存为txt文件，测试如下代码："""
import numpy as np
import jieba
from wordcloud import WordCloud
from PIL import Image


def chinese_jieba(txt):
    wordlist_jieba = jieba.cut(txt)  # 将⽂本分割，返回列表
    txt_jieba = " ".join(wordlist_jieba)  # 将列表拼接为以空格为间断的字符串
    return txt_jieba


stopwords = {'这些': 0, '那些': 0, '因为': 0, '所以': 0}  # 过滤停⽤词,根据文本，可以自己增加，形式为 '词'：0
backgroud_Image = np.array(Image.open('resources/air2.jpg'))
with open('resources/wordCloud.txt', encoding='utf8') as fp:
    txt = fp.read()
    cutted_text = chinese_jieba(txt)
    wordcloud = WordCloud(font_path=r'C:\Windows\Fonts\STKAITI.TTF',  # 字
                          background_color='white',  # 背景⾊
                          max_words=2000,  # 最⼤显示单词数
                          max_font_size=80,  # 频率最⼤单词字体⼤⼩
                          mask=backgroud_Image,
                          stopwords=stopwords,  # 过滤停⽤词
                          color_func=None,  # 设置关键字的字体颜色
                          random_state=40,  # 设置有多少种随机生成状态，即有多少种配色方案
                          ).generate(cutted_text)
    image = wordcloud.to_image()
    image.show()
